<template>
  <div class="weapon-process">
    <div class="page-title">装备数据加工</div>

    <!-- 处理控制面板 -->
    <div class="page-card control-panel">
      <div class="control-content">
        <!-- 批次配置 -->
        <div class="control-item">
          <label>批次大小：</label>
          <el-input-number
            v-model="batchSize"
            :min="1"
            :max="50"
            controls-position="right"
            size="default"
          />
        </div>

        <!-- 待处理统计 -->
        <div class="control-item">
          <el-tag type="info" size="large">
            <span style="font-weight: 600;">待处理：{{ totalPending }} 条</span>
          </el-tag>
        </div>

        <!-- 处理进度 -->
        <div class="control-item progress-item" v-if="processStats.total > 0">
          <div class="progress-content">
            <div class="progress-info">
              <span class="progress-label">处理进度</span>
              <span class="progress-stats">
                已处理 <strong>{{ processStats.processed }}</strong> / 总计 <strong>{{ processStats.total }}</strong>
              </span>
              <span class="progress-percent">{{ processStats.percentage }}%</span>
            </div>
            <el-progress
              :percentage="processStats.percentage"
              :color="progressColor"
              :stroke-width="10"
              :show-text="false"
            />
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="control-item action-buttons">
          <el-button
            type="primary"
            :icon="Tools"
            :loading="processing"
            @click="handleProcessBatch"
          >
            处理一批
          </el-button>
          <el-button
            :icon="Refresh"
            @click="loadPendingList"
          >
            刷新列表
          </el-button>
        </div>
      </div>

      <!-- 处理结果 -->
      <el-alert
        v-if="processResult"
        :title="processResult.success ? '✓ 处理完成' : '✗ 处理失败'"
        :type="processResult.success ? 'success' : 'error'"
        :closable="true"
        @close="processResult = null"
        style="margin-top: 16px"
      >
        <div v-if="processResult.success">
          <span v-if="processResult.totalCount !== undefined">总数: {{ processResult.totalCount }} </span>
          <span v-if="processResult.successCount !== undefined">成功: {{ processResult.successCount }} </span>
          <span v-if="processResult.failCount !== undefined">失败: {{ processResult.failCount }}</span>
          <span v-if="processResult.message">{{ processResult.message }}</span>
        </div>
        <div v-else>
          {{ processResult.message }}
        </div>
      </el-alert>
    </div>

    <!-- 待处理列表 -->
    <div class="page-card list-panel">
      <div class="list-header">
        <h3>待处理列表</h3>
      </div>
      
      <el-table
        :data="pendingList"
        v-loading="loading"
        style="width: 100%"
        stripe
        :height="570"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="装备名称" min-width="300" show-overflow-tooltip />
        <el-table-column label="数据来源" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.data_source">{{ row.data_source }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="介绍预览" min-width="400">
          <template #default="{ row }">
            <div 
              class="description-preview clickable"
              @click="showDescriptionDetail(row)"
              title="点击查看完整介绍"
            >
              <span>{{ row.description?.substring(0, 100) || '无介绍' }}{{ row.description?.length > 100 ? '...' : '' }}</span>
              <el-icon class="view-icon" v-if="row.description"><View /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="处理状态" width="110" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.process_status)" size="small">
              {{ getStatusText(row.process_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :loading="processingIds.has(row.id)"
              @click="handleProcessSingle(row.id)"
            >
              处理
            </el-button>
            <el-button
              type="danger"
              size="small"
              :disabled="processingIds.has(row.id)"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalPending"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadPendingList"
          @current-change="loadPendingList"
        />
      </div>
    </div>

    <!-- 介绍详情对话框 -->
    <el-dialog
      v-model="descriptionDialogVisible"
      title="装备介绍详情"
      width="70%"
      :destroy-on-close="true"
    >
      <div class="description-detail">
        <h4>{{ currentWeapon?.name }}</h4>
        <el-divider />
        <div class="markdown-content" v-html="renderMarkdown(currentWeapon?.description)"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Tools, Refresh, View } from '@element-plus/icons-vue'
import { weaponApi } from '@/api/weapon'
import { marked } from 'marked'
import DOMPurify from 'dompurify'

const loading = ref(false)
const processing = ref(false)
const batchSize = ref(5)
const currentPage = ref(1)
const pageSize = ref(20)
const totalPending = ref(0)
const pendingList = ref([])
const processResult = ref(null)
const processingIds = ref(new Set())
const descriptionDialogVisible = ref(false)
const currentWeapon = ref(null)

const processStats = reactive({
  total: 0,
  pending: 0,
  completed: 0,
  failed: 0,
  processing: 0,
  processed: 0,
  percentage: 0
})

const progressColor = computed(() => {
  const percentage = processStats.percentage
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
})

// 加载待处理列表
const loadPendingList = async () => {
  loading.value = true
  try {
    const result = await weaponApi.getPendingList(currentPage.value, pageSize.value)
    pendingList.value = result.data || []
    totalPending.value = result.total || 0
    
    // 同时加载统计信息
    await loadStatistics()
  } catch (error) {
    ElMessage.error('加载失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStatistics = async () => {
  try {
    const result = await weaponApi.getProcessStatistics()
    Object.assign(processStats, result)
  } catch (error) {
    console.error('加载统计失败:', error)
  }
}

// 处理一批
const handleProcessBatch = async () => {
  if (totalPending.value === 0) {
    ElMessage.warning('没有待处理的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要处理一批（${batchSize.value}条）记录吗？处理过程可能需要较长时间。`,
      '确认处理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  processing.value = true
  processResult.value = null

  try {
    const result = await weaponApi.processBatch(batchSize.value)
    processResult.value = result

    if (result.success) {
      ElMessage.success('批量处理完成')
      await loadPendingList()
    } else {
      ElMessage.error(result.message || '处理失败')
    }
  } catch (error) {
    ElMessage.error('处理失败: ' + error.message)
    processResult.value = {
      success: false,
      message: error.message
    }
  } finally {
    processing.value = false
  }
}

// 处理单条
const handleProcessSingle = async (id) => {
  processingIds.value.add(id)

  try {
    const result = await weaponApi.processSingle(id)
    
    if (result.success) {
      ElMessage.success('处理成功')
      await loadPendingList()
    } else {
      ElMessage.error(result.message || '处理失败')
    }
  } catch (error) {
    ElMessage.error('处理失败: ' + error.message)
  } finally {
    processingIds.value.delete(id)
  }
}

// 删除记录
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条记录吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  try {
    const result = await weaponApi.deleteRecord(id)
    
    if (result.success) {
      ElMessage.success('删除成功')
      await loadPendingList()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error) {
    ElMessage.error('删除失败: ' + error.message)
  }
}

// 显示介绍详情
const showDescriptionDetail = (weapon) => {
  currentWeapon.value = weapon
  descriptionDialogVisible.value = true
}

// 渲染 Markdown
const renderMarkdown = (markdown) => {
  if (!markdown) return '<p class="empty-text">暂无内容</p>'
  
  try {
    marked.setOptions({
      breaks: true,
      gfm: true
    })
    
    const html = marked.parse(markdown)
    return DOMPurify.sanitize(html)
  } catch (error) {
    console.error('Markdown 渲染失败:', error)
    return '<p class="error-text">Markdown 格式错误</p>'
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'info',
    processing: 'warning',
    completed: 'success',
    failed: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    failed: '失败'
  }
  return statusMap[status] || status
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  loadPendingList()
})
</script>

<style lang="scss" scoped>
.weapon-process {
  .control-panel {
    margin-bottom: 20px;
  }

  .control-content {
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
  }

  .control-item {
    display: flex;
    align-items: center;
    gap: 10px;

    label {
      font-weight: 500;
      color: #606266;
      white-space: nowrap;
    }

    &.progress-item {
      flex: 1;
      min-width: 300px;
    }

    &.action-buttons {
      margin-left: auto;
    }
  }

  .progress-content {
    width: 100%;
  }

  .progress-info {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;
    font-size: 14px;

    .progress-label {
      font-weight: 600;
      color: #303133;
    }

    .progress-stats {
      color: #606266;
      
      strong {
        color: #409eff;
        font-weight: 600;
      }
    }

    .progress-percent {
      margin-left: auto;
      font-weight: 600;
      color: #409eff;
      font-size: 16px;
    }
  }

  .list-panel {
    .list-header {
      margin-bottom: 16px;
      
      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
      }
    }
  }

  .description-preview {
    position: relative;
    padding-right: 24px;

    &.clickable {
      cursor: pointer;
      color: #409eff;

      &:hover {
        text-decoration: underline;
      }
    }

    .view-icon {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .description-detail {
    h4 {
      margin: 0 0 10px;
      font-size: 18px;
      font-weight: 600;
    }
  }

  .markdown-content {
    max-height: 600px;
    overflow-y: auto;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;

    :deep(h1) {
      font-size: 24px;
      margin: 20px 0 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
    }

    :deep(h2) {
      font-size: 20px;
      margin: 18px 0 12px;
      padding-bottom: 8px;
      border-bottom: 1px solid #f0f0f0;
    }

    :deep(h3) {
      font-size: 18px;
      margin: 16px 0 10px;
    }

    :deep(p) {
      margin: 8px 0;
      line-height: 1.8;
    }

    :deep(ul), :deep(ol) {
      margin: 10px 0;
      padding-left: 25px;
    }

    :deep(li) {
      margin: 5px 0;
      line-height: 1.6;
    }

    :deep(blockquote) {
      margin: 10px 0;
      padding: 10px 15px;
      border-left: 4px solid #409eff;
      background-color: rgba(64, 158, 255, 0.1);
    }

    :deep(code) {
      padding: 2px 6px;
      background-color: rgba(0, 0, 0, 0.05);
      border-radius: 3px;
      font-family: 'Courier New', monospace;
    }

    :deep(table) {
      width: 100%;
      margin: 15px 0;
      border-collapse: collapse;

      th, td {
        padding: 8px 12px;
        border: 1px solid #ddd;
      }

      th {
        background-color: #f4f4f5;
        font-weight: bold;
      }
    }
  }

  :deep(.el-alert) {
    span {
      margin-right: 12px;
    }
  }
}
</style>

